package com.mastermind.totalexpenditure.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHandler extends SQLiteOpenHelper
{
	
	
	private static final String DATABASE_NAME = "total_expenditure";

	private static final int DATABASE_VERSION = 1;

	public DBHandler(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {

		createDatabaseAndTables(db);
	}

	public boolean isOpen() {
		SQLiteDatabase db = getReadableDatabase();
		if (db.isOpen()) {
			db.close();
			return true;
		}
		db.close();
		return false;
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("drop table if exist " + Configuration_tbl.NAME);
		onCreate(db);
	}

	public void createDatabaseAndTables(SQLiteDatabase db) {
		Configuration_tbl.createTable(db);
	}

//	public void insertLanguage(String language) {
//		SQLiteDatabase db = getWritableDatabase();
//		ContentValues vl = new ContentValues();
//		vl.put(Configuration_tbl.Column.LANGUAGE, language);
//		db.insert(Configuration_tbl.NAME, null, vl);
//		db.close();
//	}

	public String getLanguageConfiguration() {
		SQLiteDatabase db = getWritableDatabase();
		Cursor cursor = db.rawQuery("select * from " + Configuration_tbl.NAME, null);
		if (cursor.getCount() == 0) {
			cursor.close();
			db.close();
			return "vi";
		}
		cursor.moveToFirst();
		String language = cursor.getString(cursor
					.getColumnIndex(Configuration_tbl.Column.LANGUAGE));
		db.close();
		return language;
	}

	public void updateSongName(long l, String song_name) {
		SQLiteDatabase db = getWritableDatabase();
		ContentValues vl = new ContentValues();
		vl.put(Configuration_tbl.Column.LANGUAGE, song_name);
		db.update(Configuration_tbl.NAME, vl, null, null);
		db.close();
	}

	public static class Configuration_tbl {
		//just for creating template table structure with one field
		public static final String NAME = "configuration_tbl";
		public static void createTable(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE  " + NAME + "(" + Column.ID
					+ " INTEGER PRIMARY KEY AUTOINCREMENT , "
					+ Column.LANGUAGE + " TEXT " + ");");
		}

		public class Column {
			public static final String ID = "_cid";
			public static final String LANGUAGE = "language";

		}
	}

}

